import requests
import  re
import os,csv

filename = r'music\\'
if not os.path.exists(filename):
    os.mkdir(filename)

url = 'https://music.163.com/discover/toplist?id=3778678'

# headers请求头用来伪装python代码，把他伪装成一个浏览器对服务器发送请求
headers ={
        "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36"
}
response = requests.get(url,headers=headers)
# print(response.text)
html_data = re.findall('<li><a href="/song\?id=(\d+)">(.*?)</a>',response.text)
# print(html_data)
for num_id,title in html_data:
    music_url = f'http://music.163.com/song/media/outer/url?id={num_id}.mp3' # 已经失效，网易云已经加密，302 + 防盗链 + 参数签名
    # https://music.163.com/song/media/outer/url?id=2600493765.mp3   直接返回404 / 403
    music_content = requests.get(music_url,headers=headers).content
    print(num_id,title)
    with open(os.path.join(filename, title + '.mp3'), 'wb') as f:
        f.write(music_content)



# 把一首歌保存成一个文件
# for num_id,title in html_data:
#     print(num_id,title)
#     with open(filename + title, 'w',encoding='utf-8')as f:
#         f.write(f'{num_id}\t{title}\n')
#

# 把所有歌保存到一个文件里面
# with open(os.path.join(filename, '网易云热歌榜.txt'), 'w', encoding='utf-8') as f:
#     for num_id, title in html_data:
#         f.write(f'{num_id}\t{title}\n')


# 保存为csv格式，方便以表格形式打开
# with open(os.path.join(filename, '网易云热歌榜.csv'), 'w', newline='', encoding='utf-8-sig') as f:
#     # encoding='utf-8-sig': 为了 Excel 双击打开不乱码，  utf-8:中文乱码（Win 版 Excel），  gbk:仅 Windows 简体系统，跨平台易翻车
#     writer = csv.writer(f)
#     writer.writerow(['歌曲ID', '歌名'])
#     writer.writerows(html_data)